﻿using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace Birkelund.QueryStrings.Internals
{
    internal class HashChecksumCalculator : IChecksumCalculator
    {
        public string CalculateCheckSum(IEnumerable<TokenKeyValue> allTokens)
        {
            ArgumentValidation.ThrowIfNull(allTokens, "allTokens");

            using (HashAlgorithm algorithm = HashAlgorithm.Create()) //HashAlgorithm.Create() will by default create SHA1CryptoServiceProvider
            {
                StringBuilder sb = new StringBuilder();
                int positionSalt = 1;
                foreach (TokenKeyValue token in allTokens)
                {
                    string part = token.Key + token.Value + (positionSalt++);
                    string hash = CreateHash(algorithm, part);
                    sb.Append(hash);
                }

                string hashValue = CreateHash(algorithm, sb.ToString());
                return hashValue;
            }
        }

        private string CreateHash(HashAlgorithm algorithm, string input)
        {
            byte[] inputBytes = Encoding.ASCII.GetBytes(input);
            byte[] hashBytes = algorithm.ComputeHash(inputBytes);

            // Convert the byte array to hexadecimal string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("X2")); //change to "x2" for lowercase
            }
            return sb.ToString();
        }
    }
}
